import { getForbidFlyRegion, getLimitFlyRegion, getApplyCoverage, getPlatformData } from '@/api/home'

import { useDigitalTwinStore } from '@/stores/digitalTwin'

const digitalTwinStore = useDigitalTwinStore()
const hideLayer = ['手工模型', 'cim2建筑', '苏州地形影像_Water']

// 初始化
export const initScopeLayer = async () => {
  // 设置环境参数
  const cameraParam = [554876.14875, 3386383.881719, 104995.88, -54.943035, -89.999977, 2]
  await fdapi.camera.set(cameraParam)

  //样式调整：a.打开黑暗模式  b.隐藏手工模型  c.调整地形影像的亮度
  await fdapi.weather.setDarkMode(true)
  await fdapi.infoTree.hide(hideLayer.map(name => digitalTwinStore.infoTreeObj[name]))
  await fdapi.tileLayer.setStyle(digitalTwinStore.infoTreeObj['大地形影像'], null, null, null, 0.2)
  await fdapi.tileLayer.setStyle(digitalTwinStore.infoTreeObj['苏州地形影像_Terrain'], null, null, null, 0.5)

  addRestrictFlyLayer()
  addApplyCoverage()
  addPlatformLayer()
}

// 添加限飞范围
export const addRestrictFlyLayer = async () => {
  // geojson绘制限飞范围
  addForbidFlyRegion()
  addLimitFlyRegion()
}
// 添加禁飞区
const addForbidFlyRegion = async () => {
  const { data } = await getForbidFlyRegion()
  const feature = data.features[0]
  feature.properties.height = 3000
  //分类渲染器
  let classBreaksRenderer = {
    //材质样式
    style: 16,
    //默认符号化配置
    defaultSymbol: {
      //符号化类型枚举：0 simple-marker圆形点填充  1 simple-line线填充  2 simple-fill面填充 3 polygon3d填充
      symbolType: 2,
      //填充色
      color: [1, 0, 0, 0.5],
      //轮廓线
      outline: {
        //线宽
        width: 1,
        //颜色
        color: [1, 0, 0, 1]
      }
    },
    //按field高度属性拉高面
    visualVariables: [
      {
        //控制可视化显示的类型：高度
        type: VisualType.Height,
        //属性字段名称
        field: 'height',
        //属性字段类型
        fieldType: FieldType.Number
      }
    ]
  }

  //用分类渲染器添加GeoJSONLayer
  fdapi.geoJSONLayer.add({
    id: 'forbidFlyRegion_geojson',
    visible: true, //加载后是否显示
    rotation: [0, 0, 0], //图层旋转
    offset: [0, 0, 10], //基于原始位置的偏移量
    needProject: false, //开启投影转换
    onTerrain: false, //是否贴地
    collision: true, //开启碰撞
    sourceJson: data,
    renderer: classBreaksRenderer
  })
}
// 添加限飞区
const addLimitFlyRegion = async () => {
  const { data } = await getLimitFlyRegion()
  const feature = data.features[0]
  feature.properties.height = 120
  //分类渲染器
  let classBreaksRenderer = {
    //材质样式
    style: 16,
    //默认符号化配置
    defaultSymbol: {
      //符号化类型枚举：0 simple-marker圆形点填充  1 simple-line线填充  2 simple-fill面填充 3 polygon3d填充
      symbolType: 2,
      //填充色
      color: [0, 0, 0, 0.3],
      //轮廓线
      outline: {
        //线宽
        width: 1,
        //颜色
        color: [0.5, 0.5, 0.5, 1]
      }
    },
    //按field高度属性拉高面
    visualVariables: [
      {
        //控制可视化显示的类型：高度
        type: VisualType.Height,
        //属性字段名称
        field: 'height',
        //属性字段类型
        fieldType: FieldType.Number
      }
    ]
  }

  //用分类渲染器添加GeoJSONLayer
  fdapi.geoJSONLayer.add({
    id: 'LimitFlyRegion_geojson',
    visible: true, //加载后是否显示
    rotation: [0, 0, 0], //图层旋转
    offset: [0, 0, 10], //基于原始位置的偏移量
    needProject: false, //开启投影转换
    onTerrain: false, //是否贴地
    collision: true, //开启碰撞
    sourceJson: data,
    renderer: classBreaksRenderer
  })
}

const polygonIds: string[] = []
// 添加申请范围
export const addApplyCoverage = async () => {
  // polygon添加
  const { data } = await getApplyCoverage()
  const feature = data.features[0]
  const coordinates = feature.geometry.coordinates

  const polygonList: any = []
  coordinates.forEach((c: any, index: number) => {
    let p1 = {
      id: 'applyCoverage_' + index,
      coordinates: c,
      coordinateType: 0, //坐标系类型，取值范围：0为Projection类型，1为WGS84类型，2为火星坐标系(GCJ02)，3为百度坐标系(BD09)，默认值：0
      range: [0, 1000000], //可视范围：[近裁距离, 远裁距离]，取值范围: [任意负值, 任意正值]
      color: [19 / 255, 103 / 255, 136 / 255, 0.5], //多边形的填充颜色
      frameColor: [0, 195 / 255, 255 / 255, 1],
      frameThickness: 200, //边框厚度
      intensity: 2, //亮度
      style: 0, //单色 请参照API开发文档选取枚举
      depthTest: false, //是否做深度检测 开启后会被地形高度遮挡
      priority: 1 //显示优先级 值越大显示越靠上
    }
    polygonIds.push(p1.id)
    polygonList.push(p1)
  })

  fdapi.polygon.add(polygonList)
}
// 添加无人机平台
export const addPlatformLayer = async () => {
  // marker添加
  const { data } = await getPlatformData()
  const markerList: any = []
  data.features.forEach((item: any, index: number) => {
    const coordinate = item.geometry.coordinates
    const size = 0.8
    let o1 = {
      id: 'platform_marker_' + index,
      groupId: 'platform_marker',
      coordinate: coordinate, //坐标位置
      coordinateType: 0, //默认0是投影坐标系，也可以设置为经纬度空间坐标系值为1
      anchors: [(-56 / 2) * size, 72 * size], //锚点，设置Marker的整体偏移，取值规则和imageSize设置的宽高有关，图片的左上角会对准标注点的坐标位置。示例设置规则：x=-imageSize.width/2，y=imageSize.height
      imageSize: [56 * size, 72 * size], //图片的尺寸
      range: [1, 10000000], //可视范围
      imagePath: '@path:孪创城市/无人机.png', //显示图片路径

      autoHidePopupWindow: true, //失去焦点后是否自动关闭弹出窗口
      autoHeight: false, // 自动判断下方是否有物体
      displayMode: 1, //智能显示模式  开发过程中请根据业务需求判断使用四种显示模式
      clusterByImage: true, // 聚合时是否根据图片路径分类，即当多个marker的imagePath路径参数相同时按路径对marker分类聚合
      priority: 0, //避让优先级
      occlusionCull: false //是否参与遮挡剔除
    }
    markerList.push(o1)
  })

  fdapi.marker.add(markerList)
}

//  切换显示隐藏-限飞范围
export const changeRestrictFlyLayer = async (show: boolean) => {
  if (show) {
    fdapi.geoJSONLayer.show(['forbidFlyRegion_geojson', 'LimitFlyRegion_geojson'])
  } else {
    fdapi.geoJSONLayer.hide(['forbidFlyRegion_geojson', 'LimitFlyRegion_geojson'])
  }
}
//  切换显示隐藏-申请范围
export const changeApplyCoverage = async (show: boolean) => {
  if (show) {
    fdapi.polygon.show(polygonIds)
  } else {
    fdapi.polygon.hide(polygonIds)
  }
}
//  切换显示隐藏-无人机平台
export const changePlatformLayer = async (show: boolean) => {
  if (show) {
    fdapi.marker.showByGroupId('platform_marker')
  } else {
    fdapi.marker.hideByGroupId('platform_marker')
  }
}

// 清除所有图层
export const exitScopeLayer = async () => {
  await fdapi.weather.setDarkMode(false)
  await fdapi.infoTree.show(hideLayer.map(name => digitalTwinStore.infoTreeObj[name]))
  await fdapi.tileLayer.setStyle(digitalTwinStore.infoTreeObj['大地形影像'], null, null, null, 0.3)
  await fdapi.tileLayer.setStyle(digitalTwinStore.infoTreeObj['苏州地形影像_Terrain'], null, null, null, 1)

  fdapi.geoJSONLayer.delete(['forbidFlyRegion_geojson', 'LimitFlyRegion_geojson'])
  fdapi.polygon.delete(polygonIds)
  fdapi.marker.deleteByGroupId('platform_marker')
}
